package com.dtda.edu.miaosha.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dtda.edu.miaosha.bo.MarketBo;
import com.dtda.edu.miaosha.dao.ItemPoMapper;
import com.dtda.edu.miaosha.po.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dtda.edu.miaosha.bo.ItemBo;
import com.dtda.edu.miaosha.bo.OrderBo;
import com.dtda.edu.miaosha.bo.UserInfoBo;
import com.dtda.edu.miaosha.common.SeqEnum;
import com.dtda.edu.miaosha.common.exception.BusinessException;
import com.dtda.edu.miaosha.common.response.EmBusinessError;
import com.dtda.edu.miaosha.dao.OrderPoMapper;
import com.dtda.edu.miaosha.dao.SequencePoMapper;
import com.dtda.edu.miaosha.service.ItemService;
import com.dtda.edu.miaosha.service.OrderService;
import com.dtda.edu.miaosha.service.UserService;

/**
 * @author 袁强
 * @version 2019年2月26日 下午4:50:45
 * 类说明  
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

	@Autowired
	private ItemService itemService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrderPoMapper orderPoMapper;
	@Autowired
	private SequencePoMapper sequencePoMapper;
	@Autowired
	private ItemPoMapper itemPoMapper;
	
	@Transactional
	public OrderBo createOrder(Integer userId,Integer marketId, Integer itemId, Integer itemAmount) throws BusinessException {
		// TODO Auto-generated method stub
		//校验下单状态:用户是否合法,商品是否存在,数量是否正确,校验活动商品
		ItemBo itemBo = itemService.showItemById(itemId);
		if(itemBo == null) {
			throw new BusinessException(EmBusinessError.PARAM_VALIDATION_ERROR,"商品不存在");
		}
		UserInfoBo userInfoBo = userService.getUserById(userId);
		if(userInfoBo == null) {
			throw new BusinessException(EmBusinessError.PARAM_VALIDATION_ERROR,"用户不存在");
		}
		if(itemAmount < 0 || itemAmount > 100) {
			throw new BusinessException(EmBusinessError.PARAM_VALIDATION_ERROR,"购买数量不正确");
		}
		/**1.是否传入活动商品id
		 * 2.传入的活动商品id是否和该商品一致
		 * 3.该活动是否进行中
		 */
		if(marketId != null) {
			if(marketId.intValue() != itemBo.getMarketBo().getId()) {
				throw new BusinessException(EmBusinessError.PARAM_VALIDATION_ERROR,"没有该活动");
			}else if(itemBo.getMarketBo().getMarketStatus().intValue() != 1) {
				throw new BusinessException(EmBusinessError.PARAM_VALIDATION_ERROR,"活动还未开始");
			}
		}
		//落单减库存[,支付减库存]
		boolean updateStock = itemService.decreaseStock(itemId, itemAmount);
		if(!updateStock) {
			throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
		}
		//增加销量
		boolean updateSales = itemService.updateSales(itemId, itemAmount);
		if(!updateSales) {
			throw new BusinessException(EmBusinessError.ADD_SALES_FAIL);
		}
		//订单入库
		OrderBo orderBo = new OrderBo();
		if(marketId == null) {
			orderBo.setMarketId(0);
		}else {
			orderBo.setMarketId(marketId);
		}
		orderBo.setItemId(itemId);
		orderBo.setUserId(userId);
		orderBo.setItemAmount(itemAmount);
		if(marketId != null) {
			orderBo.setItemPrice(itemBo.getMarketBo().getMarketItemPrice());
		}else {
			orderBo.setItemPrice(itemBo.getPrice());
		}
		orderBo.setOrderPrice(orderBo.getItemPrice().multiply(new BigDecimal(itemAmount)));
		//生成交易流水号,即订单号
		orderBo.setId(generateOrderNo());
		OrderPo orderPo = new OrderPo();
		BeanUtils.copyProperties(orderBo, orderPo);
		orderPo.setItemPrice(orderBo.getItemPrice().doubleValue());
		orderPo.setOrderPrice(orderBo.getOrderPrice().doubleValue());
		orderPo.setOrderTime(new Date());
		int i = orderPoMapper.insertSelective(orderPo);
		if(i > 0) {
			return orderBo;
		}
		//返回前端
		return null;
	}
	
	private String generateOrderNo() {
		StringBuffer stringBuffer = new StringBuffer();
		/**
		 * 订单号为16位
		 * 前8位为时间信息,年月日
		 * 中间6位为自增序列
		  * 后2位为分库分表位
		 */
		LocalDateTime now = LocalDateTime.now();   //java8 获取当前时间
		String nowDate = now.format(DateTimeFormatter.ISO_DATE).replaceAll("-", "");  //2019-02-27 
		stringBuffer.append(nowDate);
		//获取sequence 自增序列
		SequencePo sequencePo = sequencePoMapper.selectBySeqName(SeqEnum.ORDERID.toString());
		Integer currentValue = sequencePo.getCurrentValue();
		//判断当前值是否大于最大值,否则取初始值
		if(currentValue > sequencePo.getMaxValue()) {
			currentValue = sequencePo.getInitValue();
		}
		//必须对表进行跟新
		sequencePo.setCurrentValue(currentValue + sequencePo.getStep());
		sequencePoMapper.updateByPrimaryKeySelective(sequencePo);
		//6位拼接
		for(int i=0;i<6-(String.valueOf(currentValue).length());i++) {
			stringBuffer.append(0);
		}
		stringBuffer.append(currentValue);
		//最后的分库分表位不考虑,以00代替
		String subTable = "00";
		stringBuffer.append(subTable);
		return stringBuffer.toString();
	}
	@Override
	public List<OrderBo> selectOrderByUserId(Integer userId) {
		List<OrderBo> orderBos = new ArrayList<OrderBo>();
		List<OrderPo> orderPos = orderPoMapper.selectByUserId(userId);
		for (OrderPo orderPo:orderPos) {
			ItemPo itemPo = itemPoMapper.selectByPrimaryKey(orderPo.getItemId());
			ItemBo itemBo = new ItemBo();
			BeanUtils.copyProperties(itemPo,itemBo);
			OrderBo orderBo = new OrderBo();
			BeanUtils.copyProperties(orderPo,orderBo);
			orderBo.setOrderPrice(BigDecimal.valueOf(orderPo.getOrderPrice()));
			orderBo.setItemBo(itemBo);
			orderBos.add(orderBo);
		}
		return orderBos;
	}

}
